package com.wk.springbootlearn.common.aop;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.google.gson.Gson;
import com.wk.springbootlearn.pojo.constant.CodeConstant;
import com.wk.springbootlearn.pojo.constant.MsgConstant;
import com.wk.springbootlearn.common.model.CommonLog;
import com.wk.springbootlearn.common.model.Response;
import com.wk.springbootlearn.common.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Response res = new Response();
        int errCode = CodeConstant.JWT_VERIFY_ERROR;
        String method = request.getMethod();
        String requestURI = request.getRequestURI();
        String ip = request.getRemoteAddr();
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken == null) {
            String logInfo = new CommonLog().setHttpMethod(method).setUrl(requestURI).setIp(ip).setErrorCode(errCode).setErrorMsg(MsgConstant.INVALID_SIGNATURE).toString();
            log.error(logInfo);
            res.setCode(errCode).setMsg(MsgConstant.NOT_FOUND_SIGNATURE).setSuceess(false);
        }else {
            CommonLog commonLog = new CommonLog().setHttpMethod(method).setUrl(requestURI).setIp(ip).setErrorCode(errCode);
            try{
                String[] token = bearerToken.split(" ");
                JwtUtils.verifyToken(token[1]);
                String userId = JwtUtils.getTokenUserId(token[1]).asString();
                request.setAttribute("userId", new Long(userId));
                return true;
            }catch (SignatureVerificationException e) {
                String logInfo = commonLog.setErrorMsg(MsgConstant.INVALID_SIGNATURE).setErrorDetail(e.getMessage()).setErrorTrace(ExceptionUtils.getStackTrace(e)).toString();
                log.error(logInfo);
                res.setErr(e.getMessage()).setCode(errCode).setMsg(MsgConstant.INVALID_SIGNATURE);
            }catch (TokenExpiredException e) {
                String logInfo = commonLog.setErrorMsg(MsgConstant.INVALID_SIGNATURE).setErrorDetail(e.getMessage()).setErrorTrace(ExceptionUtils.getStackTrace(e)).toString();
                log.error(logInfo);
                res.setErr(e.getMessage()).setCode(errCode).setMsg(MsgConstant.TOKEN_EXPIRED);
            }catch (AlgorithmMismatchException e) {
                String logInfo = commonLog.setErrorMsg(MsgConstant.TOKEN_ALGORITHM_DIFF).setErrorDetail(e.getMessage()).setErrorTrace(ExceptionUtils.getStackTrace(e)).toString();
                log.error(logInfo);
                res.setErr(e.getMessage()).setCode(errCode).setMsg(MsgConstant.TOKEN_ALGORITHM_DIFF);
            }catch (Exception e) {
                String logInfo = commonLog.setErrorMsg(MsgConstant.TOKEN_INVALID).setErrorDetail(e.getMessage()).setErrorTrace(ExceptionUtils.getStackTrace(e)).toString();
                log.error(logInfo);
                res.setErr(e.getMessage()).setCode(errCode).setMsg(MsgConstant.TOKEN_INVALID);
            }
        }
        Gson gson = new Gson();
        String resJson = gson.toJson(res);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(resJson);
        return false;
    }
}